<script setup>

import {ElButton, ElCard, ElInput, ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Plus, Refresh} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {userInfoStore} from "@/store/userInfoStore.js";
import { Picture as IconPicture } from '@element-plus/icons-vue'
import {DeleteApp, ListMyAppByPage} from "@/api/app.js";
import AddAppComponent from "@/components/admin/appAdmin/AddAppComponent.vue";
import UpdateAppComponent from "@/components/admin/appAdmin/AdminUpdateAppComponent.vue";
import {AppReviewStatus} from "@/Constant/App/appReviewStatus.js";
import {AppScoringStrategy} from "@/Constant/App/appScoringStrategy.js";
import {AppType} from "@/Constant/App/appType.js";
import router from "@/router/index.js";

const current = ref(1) //当前页
const pageSize = ref(10) //每页条数
const total = ref(20) //总条数
//分页条数据模型
const form = ref({
  id: userInfoStore().info.id, //查询人id
  appName: '', //用户昵称
  appDesc: '',//用户简介
  appType: null, // 用户角色
  scoringStrategy: null,
  reviewStatus: null, // app状态
  reviewerId: null,//审核人id
  reviewMessage: '', //审核信息
  sortField: '',//排序字段
  sortOrder: ''//排序顺序
})
const fields = ref(
    {
      "应用昵称":"appName",
      "应用类型":"appType",
      "评分策略":"scoringStrategy",
      "应用状态":"reviewStatus",
    }
)
const tableData = ref([])

const clearForm = () => {
  form.value={
    id: userInfoStore().info.id, //查询人id
    appName: '', //用户昵称
    appDesc: '',//用户简介
    appType: null, // 用户角色
    scoringStrategy: null,
    reviewStatus: null, // app状态
    reviewerId: null,//审核人id
    reviewMessage: '', //审核信息
    current : 1, //当前页
    pageSize: 3,//每页条数
    sortField: '',//排序字段
    sortOrder: ''//排序顺序
  }
}


const fetchAppList = async () => {
  const params = {
    id: (form.value.id!=null&&form.value.id>0)?form.value.id:null,
    appName: form.value.appName===""?null:form.value.appName,
    appDesc: form.value.appDesc===""?null:form.value.appDesc,//用户简介
    appType: form.value.appType===null||form.value.appType<0?null:form.value.appType, // 用户角色
    scoringStrategy: form.value.scoringStrategy===null||form.value.scoringStrategy<0?null:form.value.scoringStrategy,
    reviewStatus: form.value.reviewStatus===null||form.value.reviewStatus<0?null:form.value.reviewStatus, // app状态
    reviewMessage: form.value.reviewMessage===""?null:form.value.reviewMessage, // 审核信息
    reviewerId: form.value.reviewerId==null||form.value.reviewerId<=0?null:form.value.reviewerId,//审核人id
    sortField: form.value.sortField===""?null:form.value.sortField,//排序字段
    sortOrder: form.value.sortOrder===""?null:form.value.sortOrder,//排序顺序
    current: current.value,
    pageSize: pageSize.value
  }
  //获取用户列表
  const answer = await ListMyAppByPage(params);
  ElMessage.success("搜索成功！")
  tableData.value = answer.data.apps||[];
  total.value = answer.data.total;
  current.value = answer.data.current;
  pageSize.value = answer.data.pageSize;
  console.log("tableData: ",tableData.value)
}

onMounted(async ()=>{
  await fetchAppList();
  console.log("App_List: ",tableData.value)
})
//当每页条数发生了变化，调用此函数
const onSizeChange = async (size) => {
  pageSize.value = size;
  await fetchAppList();
};
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  current.value = num;
  await fetchAppList()
};

//添加用户
const addAppRef = ref(null);

const openAddAppDialog = async () => {
  if (addAppRef.value) {
    addAppRef.value.showAddAppDialog();
  }
};
//更新App
const updateAppRef = ref(null);
const openUpdateAppDialog = (row) => {
  if (updateAppRef.value) {
    console.log("row.id：",row.id)
    updateAppRef.value.showUpdateAppDialog(row);
  }
}
//删除用户
const DeleteForApp = async (row)=>{
  ElMessageBox.confirm(
      row.isDelete===0?'此操作将删除该应用，是否确认删除？':'此操作将恢复该用户，是否确认恢复？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        console.log(row.id)
        await DeleteApp(row.id);
        await fetchAppList();
        if(row.isDelete===0) {
          ElMessage.success("删除成功！")
        }else{
          ElMessage.success("恢复成功！")
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '按钮取消!',
        })
      })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>应用管理</span>
        <div class="extra">
          <!--# todo 这个地方当管理员点击添加用户的时候要弹出一个添加用户的框-->
          <el-button type="primary" @click="openAddAppDialog">添加app</el-button>
          <AddAppComponent ref="addAppRef" @call-parent="fetchAppList" />
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline class="App-list">
      <!--todo 这里要与后端的搜索用户的数据一致，添加一样多的搜索框 -->
      <!--      <el-form-item label="用户ID：">-->
      <!--        <el-input v-model="form.id" />-->
      <!--      </el-form-item>-->
      <el-form-item label="应用呢称：">
        <el-input v-model="form.appName" />
      </el-form-item>
      <el-form-item label="应用类型：">
        <el-select placeholder="请选择" v-model="form.appType" style="width: 240px">
          <el-option label="所有" value="-1"></el-option>
          <el-option v-for="([label,value]) in Object.entries(AppType)" :key="value" :label="label" :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="评分策略：">
        <el-select placeholder="请选择" v-model="form.scoringStrategy" style="width: 240px">
          <el-option label="所有" value="-1"></el-option>
          <el-option v-for="([label,value]) in Object.entries(AppScoringStrategy)" :key="value" :label="label" :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="应用状态：">
        <el-select placeholder="请选择" v-model="form.reviewStatus" style="width: 240px">
          <el-option label="所有" value="-1"></el-option>
          <el-option v-for="([label,value]) in Object.entries(AppReviewStatus)" :key="value" :label="label" :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序字段：">
        <el-select placeholder="请选择" v-model="form.sortField" style="width: 240px">
          <el-option v-for="([label, value]) in Object.entries(fields)" :key="value" :label= "label" :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式：">
        <el-select placeholder="请选择" v-model="form.sortOrder" style="width: 240px">
          <el-option label="升序" value="asc"></el-option>
          <el-option label="降序" value="desc"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="应用描述" >
        <el-input v-model="form.appDesc" type="textarea" style="width: 360px"/>
      </el-form-item>
      <el-form-item class="button-group">
        <el-button type="primary" @click="fetchAppList"
        >搜索</el-button
        >
        <el-button
            @click="
            clearForm();
            fetchAppList();
            ElMessage.success('重置成功！')
          "
        >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          type="index"
          label="序号"
          width="50"
      ></el-table-column>
      <el-table-column
          label="应用ID"
          prop="id"
      ></el-table-column>
      <el-table-column
          label="名称"
          prop="appName"
      ></el-table-column>
      <el-table-column
          label="描述"
          prop="appDesc"
      ></el-table-column>
      <el-table-column label="应用类型" prop="appType">
        <template #default="{ row }">
          <el-text class="mx-1"  v-if="row.appType === 0">得分类</el-text>
          <el-text class="mx-1"  v-else-if="row.appType === 1">测评类</el-text>
        </template>
      </el-table-column>
      <el-table-column label="评分策略" prop="scoringStrategy">
        <template #default="{ row }">
          <el-text class="mx-1"  v-if="row.scoringStrategy === 0">自定义</el-text>
          <el-text class="mx-1"  v-else-if="row.scoringStrategy === 1">AI评分</el-text>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" prop="reviewStatus">
        <template #default="{ row }">
          <el-text class="mx-1" type="info" v-if="row.reviewStatus === 0">待审核</el-text>
          <el-text class="mx-1" type="primary" v-else-if="row.reviewStatus === 1">通过</el-text>
          <el-text class="mx-1" type="danger" v-else-if="row.reviewStatus === 2">拒绝</el-text>
        </template>
      </el-table-column>
      <el-table-column label="审核信息" prop="reviewMessage">
      </el-table-column>
      <el-table-column label="审核时间" prop="reviewTime"> </el-table-column>
      <el-table-column label="审核人id" prop="reviewerId"> </el-table-column>
      <el-table-column label="创建时间" prop="createTime"> </el-table-column>
      <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
      <el-table-column label="状态" prop="isDelete">
        <template #default="{ row }">
          <el-text class="mx-1" type="success" v-if="row.isDelete === 0">正常</el-text>
          <el-text class="mx-1" type="danger" v-else>已删除</el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="140">
        <template #default="{ row }">
          <el-button
              :icon = Edit
              circle
              plain
              type="primary"
              @click="openUpdateAppDialog(row)" >  </el-button>
          <UpdateAppComponent ref="updateAppRef" @call-parent="fetchAppList"/>
          <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="DeleteForApp(row)"
              v-if="row.isDelete === 0"
          ></el-button>
          <el-button
              :icon="Refresh"
              circle
              plain
              type="success"
              @click="DeleteForApp(row)"
              v-if="row.isDelete === 1"
          ></el-button>
          <el-button
              :icon = Plus
              circle
              plain
              type="primary"
              @click="router.push(`/mainPage/app/detail/${row.id}`)" >  </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="current"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .App-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px; /* 表单项之间的间距 */
    align-items: center;
  }

  .App-list el-form-item {
    margin-bottom: 0; /* 移除默认的底部间距 */
  }

  .button-group {
    margin-left: auto; /* 将按钮组推到右侧 */
  }

  el-image {
    position: relative;
    z-index: 1;
  }
  .el-image-viewer__img {
    z-index: 9999 !important;
  }
}
</style>


